<template>
	<div class="productBanner-box">
		<p class="productBanner-box-title">banner信息</p>

		<div class="productBanner-box-info">
			<div class="productBanner-box-info-content">
				<div class="productBanner-box-info-content-box">
					<n-form
						:model="bannerInfoForm"
						label-placement="left"
						:label-width="125"
						require-mark-placement="right-hanging"
						size="small"
						:style="{
							maxWidth: '532px'
						}"
					>
						<n-form-item label="Banner类型：">
							<span>产品</span>
						</n-form-item>
						<n-form-item path="channel" label="投放渠道(可多选)：">
							<div style="margin-top: 8px">
								<n-checkbox-group v-model:value="bannerInfoForm.channel">
									<n-space item-style="display: flex;">
										<n-checkbox value="1" label="达人营小程序" />
										<n-checkbox value="2" label="达人营APP" />
									</n-space>
								</n-checkbox-group>
								<p class="tips">若多选投放渠道，新增后将拆分成多条渠道banner数据进行管理</p>
							</div>
						</n-form-item>
						<n-form-item path="positionType" label="展示位置：">
							<n-radio-group v-model:value="bannerInfoForm.positionType" name="radiogroup">
								<n-space>
									<n-radio :value="1">探店</n-radio>
									<n-radio :value="2">素材圈</n-radio>
								</n-space>
							</n-radio-group>
						</n-form-item>
						<n-form-item path="locationId" label="选择站点：">
							<n-select
								v-model:value="bannerInfoForm.locationId"
								:options="locationOptions"
								filterable
								@update:value="locationChange"
							/>
						</n-form-item>
						<n-form-item path="productId" label="选择产品：">
							<n-select
								v-model:value="bannerInfoForm.productId"
								:disabled="bannerInfoForm.locationId == null"
								filterable
								placeholder="选择产品"
								:options="productList"
								remote
								:clear-filter-after-select="false"
								@search="handleSearchProductList"
							/>
						</n-form-item>
						<n-form-item path="Input" label="Banner时效：">
							<n-date-picker
								type="datetimerange"
								format="yyyy-MM-dd HH:mm:ss"
								value-format="yyyy-MM-dd HH:mm:ss"
								clearable
								:is-date-disabled="updateDisablePreviousDate"
								@update:value="dateTimeChange"
							/>
						</n-form-item>
						<n-form-item path="type" label="Banner图片：">
							<n-radio-group
								v-model:value="bannerInfoForm.type"
								name="radiogroup"
								@update:value="bannerTypeChange"
							>
								<n-space>
									<n-radio :value="1">产品图</n-radio>
									<n-radio :value="2">自行上传</n-radio>
								</n-space>
							</n-radio-group>
						</n-form-item>
						<n-form-item v-if="bannerInfoForm.type === 2" label="展示图片：">
							<pictureCropper
								ref="pictureCropperRef"
								:width="presetMode.width"
								:height="presetMode.height"
								@commit="successUpload"
							></pictureCropper>
						</n-form-item>
					</n-form>
				</div>
			</div>
			<div class="productBanner-box-info-btn">
				<n-button type="info" :disabled="buttonLoading" :loading="buttonLoading" @click="confirm">
					确定
				</n-button>
			</div>
		</div>
	</div>
</template>

<script setup>
import { reactive, ref, watch } from 'vue';
import { useMessage } from 'naive-ui';
import baseConfig from '@/config';
import { getQueryParam } from '@/utils/index';
import { locationAllList, productAll, savePbanner } from '@/api/bannerMange';
import dayjs from 'dayjs';
import { useRouter, useRoute } from 'vue-router';
const Emits = defineEmits(['changImage', 'changPositionType']);
import pictureCropper from './pictureCropper';
const pictureCropperRef = ref();
const presetMode = reactive({
	width: 750,
	height: 522
});
const message = useMessage();
const router = useRouter();
const route = useRoute();

const buttonLoading = ref(false);
const headers = {
	Authorization: getQueryParam('token') ? getQueryParam('token') : baseConfig.LL_APP_TOKEN
};
const bannerInfoForm = reactive({
	channel: [],
	locationId: null,
	positionType: 1,
	productId: null,
	productTitle: null, //产品名称
	endTime: null,
	startTime: null,
	type: 1,
	content: '' //图片链接
});

const locationOptions = ref([]);
const updateDisablePreviousDate = (ts) => {
	// Banner时效：禁用
	let date = new Date();
	return (
		ts < new Date(date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate()).getTime()
	);
};
const locationList = async () => {
	let admin = route.query.admin;
	// 获取站点
	let params = {
		city: '',
		configId: null,
		admin
	};
	let res = await locationAllList(params);

	if (res && res.code === 200) {
		let list = res.data || [];
		locationOptions.value = list.map((item) => {
			item.label = item.city;
			item.value = item.id;
			return item;
		});
	}
};
locationList();

const productList = ref([]);
const currentProductItem = ref(null); //当前选中产品
const locationChange = () => {
	// 产品列表修改
	bannerInfoForm.productId = null;
	bannerInfoForm.productTitle = null;
	currentProductItem.value = null;
	handleSearchProductList();
};
const dateTimeChange = (val) => {
	// Banner时效：
	if (val) {
		bannerInfoForm.startTime = dayjs(val[0])
			.set('hour', 0)
			.set('minute', 0)
			.set('second', 0)
			.format('YYYY-MM-DD HH:mm:ss');
		bannerInfoForm.endTime = dayjs(val[1])
			.set('hour', 23)
			.set('minute', 59)
			.set('second', 59)
			.format('YYYY-MM-DD HH:mm:ss');
	} else {
		bannerInfoForm.startTime = null;
		bannerInfoForm.endTime = null;
	}
};
const bannerTypeChange = (val) => {
	if (val === 1 && currentProductItem.value) {
		// 产品图
		bannerInfoForm.content = currentProductItem.value.content;
		Emits('changImage', currentProductItem.value.content);
	} else {
		bannerInfoForm.content = '';
		Emits('changImage', '');
	}
};
watch(
	() => bannerInfoForm.positionType,
	(val) => {
		if (val == 1) {
			presetMode.width = 750;
			presetMode.height = 522;
		} else {
			presetMode.width = 710;
			presetMode.height = 322;
		}
		if (bannerInfoForm.type === 1) {
			if (currentProductItem.value) {
				// 产品图
				bannerInfoForm.content = currentProductItem.value.content;
			}
		} else {
			pictureCropperRef.value.changeImageUrl = '';
			bannerInfoForm.content = '';
		}
		Emits('changImage', bannerInfoForm.content);
		Emits('changPositionType', val);
	}
);

watch(
	() => bannerInfoForm.productId,
	(val) => {
		if (!val) {
			currentProductItem.value = '';
			bannerInfoForm.productTitle = '';
			if (bannerInfoForm.type == 1) {
				bannerInfoForm.content = '';
				Emits('changImage', '');
			}
			return;
		}
		// 选择产品：
		let data = productList.value.filter((item) => item.value == val);
		currentProductItem.value = data[0];
		bannerInfoForm.productTitle = data[0].label;
		if (bannerInfoForm.type === 1) {
			bannerInfoForm.content = data[0].content;
			Emits('changImage', data[0].content);
		}
	}
);
const successUpload = (url) => {
	bannerInfoForm.content = url;
	Emits('changImage', url);
};
const confirm = () => {
	if (!bannerInfoForm.channel.length) {
		message.error('请选择投放渠道');
		return;
	}
	if (!bannerInfoForm.locationId) {
		message.error('请选择站点');
		return;
	}

	if (!bannerInfoForm.productId && !bannerInfoForm.productTitle) {
		message.error('请选择产品');
		return;
	}

	if (!bannerInfoForm.startTime && !bannerInfoForm.endTime) {
		message.error('请选择时效');
		return;
	}

	if (bannerInfoForm.type == 2 && !bannerInfoForm.content) {
		message.error('请先上传图片');
		return;
	} else {
		let formatArr = ['png', 'jpg', 'jpeg'];
		let index = bannerInfoForm.content.lastIndexOf('.');
		let ext = bannerInfoForm.content.substr(index + 1);
		if (formatArr.indexOf(ext) === -1) {
			message.error('该图片格式暂不支持');
			return;
		}
	}

	// 确定保存
	let params = {
		...bannerInfoForm
	};
	params.type = 1; //产品banner type == 1
	buttonLoading.value = true;
	let admin = route.query.admin;
	savePbanner(params).then((res) => {
		if (res.code == 200) {
			message.success('添加成功');
		} else {
			message.error('添加失败');
		}
		if (admin) {
			router.replace({
				path: '/bannerMange/bannerListAdmin'
			});
		} else {
			router.replace({
				path: '/bannerMange/bannerList'
			});
		}
	});
};
const handleSearchProductList = async (val = '') => {
	let params = {
		locationId: bannerInfoForm.locationId,
		pageIndex: 1,
		pageSize: 50,
		keyWord: val
	};
	let res = await productAll(params);
	if (res.code === 200) {
		productList.value = res.data.productList.map((item) => {
			item.label = item.productTitle;
			item.value = item.productId;
			return item;
		});
	}
};
</script>

<style lang="less" scoped>
.productBanner-box {
	flex: 1;
	overflow-y: auto;
	display: flex;
	flex-direction: column;
	&-title {
		font-size: 20px;
		font-weight: 600;
		color: #333333;
		margin-bottom: 16px;
	}
	.tips {
		margin-top: 8px;
		font-size: 12px;
		font-family: PingFangSC-Regular, PingFang SC;
		font-weight: 400;
		color: #f5894e;
	}
	&-info {
		flex: 1;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
		background: linear-gradient(180deg, #f3f6ff 0%, #fcfdff 100%);
		border-radius: 4px;
		&-content {
			position: relative;
			flex: 1;
			&-box {
				position: absolute;
				overflow-y: auto;
				width: 100%;
				height: 100%;
				left: 0;
				top: 0;
				padding: 20px;
			}
		}
		&-btn {
			flex-shrink: 0;
			line-height: 50px;
			background: #ffffff;
			padding-left: 20px;
			border-radius: 0px 0px 4px 4px;
			border: 1px solid #f0f0f0;
		}
	}
	::v-deep(.n-form-item) {
		line-height: 1.4;
	}
}
</style>
